package com.taijihuabao.common.activititasklistener.leavelistener;

import com.taijihuabao.modules.entity.ApprovalEntity;
import com.taijihuabao.modules.entity.ApprovalHistoryEntity;
import com.taijihuabao.modules.entity.DeptUserEntity;
import com.taijihuabao.modules.enums.optenums.dept.DeptRoleEnum;
import com.taijihuabao.modules.mapper.ApprovalHistoryMapper;
import com.taijihuabao.modules.mapper.ApprovalMapper;
import com.taijihuabao.modules.mapper.DeptMapper;
import com.taijihuabao.modules.mapper.DeptUserMapper;
import org.activiti.engine.delegate.DelegateTask;
import org.activiti.engine.delegate.TaskListener;
import org.activiti.engine.task.IdentityLink;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;

/**
 * 给单个任务赋审批人
 * @author xiaob
 */
@Component
public class PersonnelDeptTaskListener implements TaskListener {

    @Resource
    private ApprovalMapper approvalMapper;
    @Resource
    private DeptUserMapper deptUserMapper;
    @Resource
    private DeptMapper deptMapper;
    @Resource
    private ApprovalHistoryMapper approvalHistoryMapper;

    @Override
    public void notify(DelegateTask delegateTask) {
        //获取审批单id
        String bussinessKey = delegateTask.getExecution().getProcessInstanceBusinessKey();
        ApprovalEntity approvalEntity = approvalMapper.selectById(Long.valueOf(bussinessKey));
        //历史表对象
        ApprovalHistoryEntity approvalHistoryEntity = new ApprovalHistoryEntity();
        approvalHistoryEntity.setApplyDeptCode(approvalEntity.getApplyDeptCode());
        approvalHistoryEntity.setApplyName(approvalEntity.getApplyName());
        approvalHistoryEntity.setApplyUserId(approvalEntity.getApplyUserId());
        approvalHistoryEntity.setApprovalCode(approvalEntity.getApprovalCode());
        approvalHistoryEntity.setApprovalFlow(delegateTask.getName());
        approvalHistoryEntity.setApprovalOpinion(null);
        approvalHistoryEntity.setApprovalState("ing");
        approvalHistoryEntity.setApprovalType(approvalEntity.getApprovalType());
        approvalHistoryEntity.setApprovalTask(delegateTask.getId());
        approvalEntity.setApprovalTask(approvalHistoryEntity.getApprovalTask());
        approvalHistoryEntity.setApprovalUserId(Long.valueOf(delegateTask.getAssignee()));
        approvalEntity.setApprovalUserId(approvalHistoryEntity.getApprovalUserId());
        //查询审批用户的部门
        List<DeptUserEntity> deptUserEntities = deptUserMapper
                .selectDeptByUserId(Long.valueOf(delegateTask.getAssignee()));
        approvalHistoryEntity.setApprovalDeptCode(deptUserEntities.get(0).getDeptCode());
        approvalEntity.setApprovalDeptCode(approvalHistoryEntity.getApprovalDeptCode());
        //新增工作流历史记录
        approvalHistoryMapper.insertApproval(approvalHistoryEntity);
        //修改工作流记录
        approvalMapper.updateApproval(approvalEntity);
    }
}
